package com.demo.netty;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory;
import org.jboss.netty.channel.local.LocalAddress;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.util.HashedWheelTimer;

import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author jasper
 */
public class ClientStart {
    public static void main(String[] args) {

        final String host = "127.0.0.1";
        final int port = 10081;
        // 服务类
        final ClientBootstrap bootstrap = new ClientBootstrap();
        // 线程池
        ExecutorService boss = Executors.newCachedThreadPool();
        ExecutorService worker = Executors.newCachedThreadPool();
        // socket工厂
        bootstrap.setFactory(new DefaultLocalClientChannelFactory());
        // 管道工厂
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decoder", new StringDecoder());
                pipeline.addLast("encoder", new StringEncoder());
                pipeline.addLast("clientHandler", new ClientHandler(bootstrap, new HashedWheelTimer()));
                return pipeline;
            }
        });
        bootstrap.setOption("tcpNoDelay", true);
        // 连接服务端
        ChannelFuture connect = bootstrap.connect(new LocalAddress(port));
        Channel channel = connect.getChannel();
        System.out.println("client start");
        MessageType messageType = new MessageType();
        messageType.setContext("hello server");
        messageType.setType(1);

        channel.write(messageType);
        Scanner scanner = new Scanner(System.in);

        while (true)
        {
            System.out.println("请输入");
            String next = scanner.next();
            String[] split = next.split(",");
            messageType.setType(Integer.parseInt(split[0]));
            messageType.setContext(split[1]);
            channel.write(messageType);
        }
    }
}
